package com.atguigu.utils;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {
        //争车位
        Semaphore semaphore = new Semaphore(10);
        for (int i = 1; i <=5 ; i++) {
            new Thread(()->{try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + "占到车位");
                try {
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3) + 1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "离开商场");
            }catch(InterruptedException e)
                {throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
